package com.timeshare.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.timeshare.dto.NoticeRequest;
import com.timeshare.entity.Notice;
import com.timeshare.mapper.NoticeMapper;
import com.timeshare.service.NoticeService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 公告服务实现
 */
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice> implements NoticeService {
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void publishNotice(Long publisherId, NoticeRequest request) {
        Notice notice = new Notice();
        BeanUtil.copyProperties(request, notice);
        notice.setPublisherId(publisherId);
        notice.setStatus(1); // 已发布
        this.save(notice);
    }
    
    @Override
    public Page<Notice> getNoticeList(Integer page, Integer size) {
        Page<Notice> noticePage = new Page<>(page, size);
        LambdaQueryWrapper<Notice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Notice::getStatus, 1) // 只查询已发布的
               .orderByDesc(Notice::getCreateTime);
        return this.page(noticePage, wrapper);
    }
    
    @Override
    public Notice getNoticeDetail(Long id) {
        Notice notice = this.getById(id);
        if (notice == null) {
            throw new RuntimeException("公告不存在");
        }
        return notice;
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateNotice(Long id, NoticeRequest request) {
        Notice notice = this.getById(id);
        if (notice == null) {
            throw new RuntimeException("公告不存在");
        }
        
        BeanUtil.copyProperties(request, notice, "id", "publisherId");
        this.updateById(notice);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteNotice(Long id) {
        Notice notice = this.getById(id);
        if (notice == null) {
            throw new RuntimeException("公告不存在");
        }
        this.removeById(id);
    }
}

